package io.renren.modules.sp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.renren.common.annotation.SeasonFilter;
import io.renren.common.exception.RenException;
import io.renren.common.interceptor.UserContext;
import io.renren.common.page.PageData;
import io.renren.common.service.impl.CrudServiceImpl;
import io.renren.common.constant.Constant;
import io.renren.common.utils.*;
import io.renren.common.utils.image.ImageTool;
import io.renren.common.utils.image.ImageTool2;
import io.renren.modules.sp.controller.SpMatchItemTeamUserController;
import io.renren.modules.sp.dao.*;
//import io.renren.modules.sp.dto.SpMatchItemScoreImport;
import io.renren.modules.sp.dto.*;
import io.renren.modules.sp.entity.*;
import io.renren.modules.sp.service.SpBaseMatchItemService;
import io.renren.modules.sp.service.SpMatchItemTeamService;
import io.renren.modules.sp.service.TAreaService;
import io.renren.modules.sys.dao.SysCommDao;
import io.renren.modules.sys.dao.SysDictDataDao;
import io.renren.modules.sys.entity.SysDictDataEntity;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 参赛队
 *
 * @author whc 15953295779@126.com
 * @since 3.0 2023-04-21
 */
@Service
public class SpMatchItemTeamServiceImpl extends CrudServiceImpl<SpMatchItemTeamDao, SpMatchItemTeamEntity, SpMatchItemTeamDTO> implements SpMatchItemTeamService {
    @Autowired
    private SpMatchItemTeamUserDao teamUserDao;
    @Autowired
    private SysCommDao commDao;
    @Autowired
    private SpMatchItemDao spMatchItemDao;
    @Autowired
    private SpMatchDao spMatchDao;
    @Autowired
    private SpUserDao spUserDao;
    @Autowired
    private TAreaService areaService;
    @Autowired
    private SpTeamDao teamDao;
    @Autowired
    private SysDictDataDao sysDictDataDao;
    @Autowired

    private SpTicketDao spTicketDao;
    @Autowired
    private SpTeamUserDao spTeamUserDao;
    @Autowired
    private SpMatchItemTeamUserDao spMatchItemTeamUserDao;
    @Autowired
    private SpCertificateImportDao spCertificateImportDao;
    @Autowired
    private CertificateNoUtils certificateNoUtils;
    @Autowired
    private SysDictDataDao dictDataDao;
    @Autowired
    private SpBaseMatchItemDao spBaseMatchItemDao;
    @Autowired
    private SpMatchItemTeamDao spMatchItemTeamDao;
    public static String CANCEL_STATUS ="(3,7,8)";

    @Override
    public QueryWrapper<SpMatchItemTeamEntity> getWrapper(Map<String, Object> params){
        QueryWrapper<SpMatchItemTeamEntity> wrapper = new QueryWrapper<>();

        String matchItemId = (String)params.get("matchItemId");
        wrapper.eq(StringUtils.isNotBlank(matchItemId), "match_item_id", matchItemId);
        String teamId = (String)params.get("teamId");
        wrapper.eq(StringUtils.isNotBlank(teamId), "team_id", teamId);
        String teamName = (String)params.get("teamName");
        wrapper.eq(StringUtils.isNotBlank(teamName), "team_name", teamName);
        String isRise = (String)params.get("isRise");
        wrapper.eq(StringUtils.isNotBlank(isRise), "is_rise", isRise);
        return wrapper;
    }

    @Override
    public Result saveMatchItemTeam(SpMatchItemTeamDTO dto) {

        SpUserDTO cuser = UserContext.getUser();
        SpTeamEntity team = teamDao.selectById(cuser.getTeamId());
        if(team.getStatus()==0){
            return  new Result().error("代表队已禁用，不能报名");
        }
        //检查代表队不能重复
        QueryWrapper<SpMatchItemTeamEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("match_item_id", dto.getMatchItemId());
        wrapper.eq("team_name", dto.getTeamName());
        List<SpMatchItemTeamEntity> list = baseDao.selectList(wrapper);
        if(list.size() > 0){
            return new Result().error("队伍名称已被使用，请更换");
        }
        for( SpMatchItemTeamUserDTO user : dto.getUsers()){
            String checkMsg = check(user.getUserId(),dto.getGroupId().longValue(),dto.getMatchItemId().longValue());
            if(checkMsg!=null){
                return new Result().error(checkMsg);
            }
        }
        SpMatchItemTeamEntity entity = new SpMatchItemTeamEntity();
        BeanUtils.copyProperties(dto, entity);

        entity.setIsRise(0);
        entity.setStatus(0);

        entity.setCreateDate(new Date());
        entity.setCreator(cuser.getId());
        entity.setSignTime(new Date());
        entity.setTeamId(cuser.getTeamId());
        baseDao.insert(entity);
        //保存参赛人员
        List<SpMatchItemTeamUserDTO> userList = dto.getUsers();
        for( SpMatchItemTeamUserDTO user : userList){

            SpMatchItemTeamUserEntity userEntity = new SpMatchItemTeamUserEntity();
            userEntity.setTeamUserId(user.getTeamUserId());
            //userEntity.setGroupId(entity.getGroupId());
            userEntity.setMatchItemTeamId(entity.getId());
            userEntity.setStatus(1);
            userEntity.setTeamId(cuser.getTeamId());
            userEntity.setUserId(user.getUserId());
            userEntity.setType(1);
            teamUserDao.insert(userEntity);
        }
        //插入指导老师
        if(StringUtils.isNotBlank(dto.getTeachers())){
            for(String teacherId : dto.getTeachers().split(",")){
                SpMatchItemTeamUserEntity teacher = new SpMatchItemTeamUserEntity();
                teacher.setMatchItemTeamId(entity.getId());
                teacher.setStatus(1);
                teacher.setTeamId(cuser.getTeamId());
                teacher.setType(2);
                teacher.setUserId(Long.parseLong(teacherId));
                teamUserDao.insert(teacher);
            }
        }
        return new Result();
    }

    public Result editMatchItemTeam(SpMatchItemTeamDTO dto) {

        SpUserDTO cuser = UserContext.getUser();
        //检查代表队不能重复
        QueryWrapper<SpMatchItemTeamEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("match_item_id", dto.getMatchItemId());
        wrapper.eq("team_name", dto.getTeamName());
        wrapper.ne("id", dto.getId());
        List<SpMatchItemTeamEntity> list = baseDao.selectList(wrapper);
        if(list.size() > 0){
            return new Result().error("队伍名称已被使用，请更换");
        }
        for( SpMatchItemTeamUserDTO user : dto.getUsers()){
            String checkMsg = check(user.getUserId(),dto.getGroupId().longValue(),dto.getMatchItemId().longValue());
            if(checkMsg!=null){
                return new Result().error(checkMsg);
            }

        }
        SpMatchItemTeamEntity entity = baseDao.selectById(dto.getId());
        BeanUtils.copyProperties(dto, entity);

        entity.setIsRise(0);
        entity.setStatus(0);


        entity.setSignTime(new Date());
        entity.setTeamId(cuser.getTeamId());
        baseDao.updateById(entity);
        //删除所有的老师
        QueryWrapper teacherQe =new QueryWrapper<>().eq("team_Id", dto.getId());
        teamUserDao.delete(teacherQe);
        //保存参赛人员
        List<SpMatchItemTeamUserDTO> userList = dto.getUsers();
        for( SpMatchItemTeamUserDTO user : userList){
            String checkMsg = check(user.getUserId(),dto.getGroupId().longValue(),dto.getMatchItemId().longValue());
            if(checkMsg!=null){
                return new Result().error(checkMsg);
            }
            SpMatchItemTeamUserEntity userEntity = new SpMatchItemTeamUserEntity();
            userEntity.setTeamUserId(user.getTeamUserId());
            //userEntity.setGroupId(entity.getGroupId());
            userEntity.setMatchItemTeamId(entity.getId());
            userEntity.setStatus(1);
            userEntity.setTeamId(cuser.getTeamId());
            userEntity.setUserId(user.getUserId());
            userEntity.setType(1);
            teamUserDao.insert(userEntity);
        }
        //插入指导老师
        if(StringUtils.isNotBlank(dto.getTeachers())){
            for(String teacherId : dto.getTeachers().split(",")){
                SpMatchItemTeamUserEntity teacher = new SpMatchItemTeamUserEntity();
                teacher.setMatchItemTeamId(entity.getId());
                teacher.setStatus(1);
                teacher.setTeamId(cuser.getTeamId());
                teacher.setType(2);
                teacher.setUserId(Long.parseLong(teacherId));
                teamUserDao.insert(teacher);
            }
        }
        return new Result();
    }

    /**
     * 个人赛
     * */
    @Transactional
    public Result saveMatchItemPerson(SpMatchItemTeamDTO dto) {
        SpUserDTO cuser = UserContext.getUser();
        SpTeamEntity team = teamDao.selectById(cuser.getTeamId());
        if(team.getStatus()==0){
            return  new Result().error("代表队已禁用，不能报名");
        }
        //保存参赛人员
        List<SpMatchItemTeamUserDTO> userList = dto.getUsers();
        for( SpMatchItemTeamUserDTO user : userList){
            String checkMsg = check(user.getUserId(),dto.getGroupId().longValue(),dto.getMatchItemId().longValue());
            if(checkMsg!=null){
                return new Result().error(checkMsg);
            }
            //插入参赛队
            SpMatchItemTeamEntity entity = new SpMatchItemTeamEntity();
            BeanUtils.copyProperties(dto, entity);
            entity.setIsRise(0);
            entity.setCreateDate(new Date());
            entity.setCreator(cuser.getId());;
            entity.setTeamId(cuser.getTeamId());
            entity.setSignTime(new Date());
            entity.setStatus(0);
            baseDao.insert(entity);
            //插入队员
            SpMatchItemTeamUserEntity userEntity = new SpMatchItemTeamUserEntity();
            userEntity.setMatchItemTeamId(entity.getId());
            userEntity.setStatus(1);
            userEntity.setTeamId(cuser.getTeamId());
            userEntity.setUserId(user.getUserId());
            userEntity.setTeamUserId(user.getUserId());
            userEntity.setCreateDate(new Date());
            //1是学生，2是老师
            userEntity.setType(1);
            teamUserDao.insert(userEntity);
            //插入指导老师
            if(StringUtils.isNotBlank(user.getTeachers())){
                for(String teacherId : user.getTeachers().split(",")){
                    SpMatchItemTeamUserEntity teacher = new SpMatchItemTeamUserEntity();
                    teacher.setMatchItemTeamId(entity.getId());
                    teacher.setStatus(1);
                    teacher.setTeamId(cuser.getTeamId());
                    //老师，2是学生
                    teacher.setType(2);
                    teacher.setUserId(Long.parseLong(teacherId));
                    teacher.setTeamUserId(Long.parseLong(teacherId));
                    teamUserDao.insert(teacher);
                }
            }
        }
        return new Result();
    }

    /**
     * 弃权
     * */
    @Transactional
    public Result cancel(SpMatchItemTeamDTO dto){
        SpMatchItemTeamEntity entity = baseDao.selectById(dto.getId());
        entity.setRejectReason("");
        // 审核中、驳回两个状态下，取消报名直接删除条目
        if(entity.getStatus()==0 || entity.getStatus()==8){
            // 取消报名直接删除记录
            baseDao.deleteById(entity);
        }else if(entity.getStatus()==5){
            // 放弃晋级: 状态改为完赛
            //entity.setStatus(2);
            entity.setRejectReason("放弃晋级");
            baseDao.updateById(entity);
        }else{
            // 7弃权
            entity.setStatus(7);
            baseDao.updateById(entity);
        }
        //baseDao.updateById(entity);
        //whc改为删掉
        return new Result();
    }

    /**
     * 生成参赛证编号
     * @param matchTeamId
     * @return
     */
    @Override
    public String generateTicketNo(Long matchTeamId) {
        /**
         * 1、 查询当前队伍的所有队员
         *     1.1、查询当前队伍的所有队员的比赛证件是否已经生成
         *     1.2、如果已经生成，则只修改参赛证图片
         *     1.3、如果没有生成，则生成参赛证图片、并保存
         * 2、生成领队的参赛证
         * 3、教练没有参赛证
         */
        //查询所有队员(选手)
        QueryWrapper userQ = new QueryWrapper();
        userQ.eq("type", 1);
        userQ.eq("match_item_team_id", matchTeamId);
        userQ.orderByAsc("id");

        List<SpMatchItemTeamUserEntity> userList = teamUserDao.selectList(userQ);
        SpMatchItemTeamEntity spMatchItemTeam = baseDao.selectById(matchTeamId);
        SpMatchItemEntity itemEntity = spMatchItemDao.selectById(spMatchItemTeam.getMatchItemId());
        SpMatchEntity matchEntity = spMatchDao.selectById(itemEntity.getMatchId());
        SpTeamEntity team = teamDao.selectById(spMatchItemTeam.getTeamId());

        //查询省份
        TAreaEntity province = areaService.getByCode(team.getProvince());
        //省份简称
        String provinceName = province.getJiancheng();
        //100301:X小学  100302:C初中 100303:G 高中 领队：L
        String groupName = spMatchItemTeam.getGroupId() == 100301 ? "X" :
                spMatchItemTeam.getGroupId() == 100302 ? "C" :
                        spMatchItemTeam.getGroupId() == 100303 ? "G" :
                                spMatchItemTeam.getGroupId() == 100304 ? "X" :
                                        spMatchItemTeam.getGroupId() == 100305 ? "X" :
                                                spMatchItemTeam.getGroupId() == 100306 ? "X" :
                                                        spMatchItemTeam.getGroupId() == 100307 ? "G" : "";
        if (province == null || StringUtils.isBlank(province.getJiancheng())) {
            return "赛事未维护省份，或者省份简称为空！";
        }
        if (StringUtils.isBlank(team.getTeamCode())) {
            return "代表队编码不能为空！";
        }
        if (StringUtils.isBlank(matchEntity.getTimes())) {
            return "赛事届数不能为空";
        }
        if (StringUtils.isBlank(groupName)) {
            return "赛项报名，参赛组别不能为空！";
        }
        if (matchEntity.getMatchLevel() == null || matchEntity.getMatchLevel() > 3 || matchEntity.getMatchLevel() < 0) {
            return "赛事级别维护错误";
        }
        //生成证件编号时不需要场地
        /*if(StringUtils.isBlank(itemEntity.getAddr())){
            return itemEntity.getId()+"比赛场地不能为空";
        }*/
        //没有生成
        char leveName = "ABC".charAt(matchEntity.getMatchLevel() - 1);
        //生成选手证件
        for (SpMatchItemTeamUserEntity user : userList) {
            Long userId = user.getUserId();
            if(userId.longValue() == 258){
                System.out.println("258");
            }
            List<Map<String,String>> tickList = isExitsTicket(matchEntity.getId(), spMatchItemTeam.getTeamId(), userId);
            //有跳过
            if (tickList != null && tickList.size() > 0) {
                Map<String, String> ticket = tickList.get(0);
                SpTicketEntity spTicketEntity = new SpTicketEntity();
                Object tid = (Object)ticket.get("id");
                if(tid instanceof Integer) {
                    spTicketEntity.setId(((Integer) tid).longValue());
                }
                spTicketEntity.setMatchName(matchEntity.getMatchName());
                spTicketEntity.setTeamName(team.getTeamName());
                spTicketEntity.setUserId(userId);
                spTicketEntity.setTicket(ticket.get("ticket"));
                //this.genAndSaveTicketUrl(spTicketEntity, "2");
                continue;
            }

            //队内序号
            String order = queryTeamMemberNum(matchEntity.getId(), spMatchItemTeam.getTeamId());
            //届数(01)+赛事级别（A B C）+地区简称(沪)+组（X C G L）+中划线（）+代表队编码（5）+队内序号（3）
            StringBuffer cardCode = new StringBuffer();
            cardCode.append(matchEntity.getTimes())
                    .append(leveName)
                    .append(provinceName)
                    .append(groupName)
                    .append("-")
                    .append(team.getTeamCode())
                    .append(order);
            SpTicketEntity spTicketEntity = new SpTicketEntity();
            spTicketEntity.setMatchId(matchEntity.getId().longValue());
            spTicketEntity.setMatchName(matchEntity.getMatchName());
            spTicketEntity.setTeamId(team.getId());
            spTicketEntity.setTeamName(team.getTeamName());
            spTicketEntity.setUserId(userId);
            spTicketEntity.setTicket(cardCode.toString());
            spTicketDao.insertTicket(spTicketEntity);
            //生成选手证件图片
            //this.genAndSaveTicketUrl(spTicketEntity,"2");
        }
        //查询领队信息
        List<SpTeamUserEntity> leaderList = spTeamUserDao.selectList(new QueryWrapper<SpTeamUserEntity>()
                .eq("team_id", spMatchItemTeam.getTeamId())
                .in("type", 1, 2)
        );
        //生成领队证件
        for (SpTeamUserEntity user : leaderList) {
            Long userId = user.getUserId();
            List<Map<String,String>> tickList = isExitsTicket(matchEntity.getId(), spMatchItemTeam.getTeamId(),userId);
            //有跳过
            if (tickList != null && tickList.size() > 0) {
                Map<String, String> ticket = tickList.get(0);
                SpTicketEntity spTicketEntity = new SpTicketEntity();
                Object tid = (Object)ticket.get("id");
                if(tid instanceof Integer) {
                    spTicketEntity.setId(((Integer) tid).longValue());
                }
                spTicketEntity.setMatchName(matchEntity.getMatchName());
                spTicketEntity.setTeamName(team.getTeamName());
                spTicketEntity.setUserId(userId);
                spTicketEntity.setTicket(ticket.get("ticket"));
                //this.genAndSaveTicketUrl(spTicketEntity, "1");
                continue;
            }
            //队内序号
            String order = queryTeamMemberNum(matchEntity.getId(), spMatchItemTeam.getTeamId());
            //届数(01)+赛事级别（A B C）+地区简称(沪)+组（X C G L）+中划线（）+代表队编码（5）+队内序号（3）
            StringBuffer cardCode = new StringBuffer();
            cardCode.append(matchEntity.getTimes())
                    .append(leveName)
                    .append(provinceName)
                    .append("L")
                    .append("-")
                    .append(team.getTeamCode())
                    .append(order);
            SpTicketEntity spTicketEntity = new SpTicketEntity();
            spTicketEntity.setMatchId(matchEntity.getId().longValue());
            spTicketEntity.setMatchName(matchEntity.getMatchName());
            spTicketEntity.setTeamId(team.getId());
            spTicketEntity.setTeamName(team.getTeamName());
            spTicketEntity.setUserId(userId);
            spTicketEntity.setTicket(cardCode.toString());
            spTicketDao.insertTicket(spTicketEntity);
            //生成证件
            //this.genAndSaveTicketUrl(spTicketEntity,"1");
        }
        return null;
    }

    private List<Map<String,String>> isExitsTicket(Long matchId,Long teamId,Long userId){
        //查询是否有入场证
        String sql = "SELECT t.* from  sp_ticket t " +
                "where t.match_id =#{p.matchId} and t.user_id =#{p.userId} and t.team_id =#{p.teamId}";
        Map<String, Object> haveParam = new HashMap<>();
        haveParam.put("matchId", matchId);
        haveParam.put("teamId", teamId);
        haveParam.put("userId", userId);
        return commDao.commList(sql, haveParam);
    }

    /**
     * 生成证件图片并保存
     * @param spTicketEntity
     * @param type  1:领队 2:选手
     * @param picType  1:证件 2:号码布 3:证件+号码布
     */
    @Override
    public void genAndSaveTicketUrl(SpTicketEntity spTicketEntity, String type, String picType) {
        // 查询用户详细信息
        SpUserEntity spUser = spUserDao.selectById(spTicketEntity.getUserId());
        // 生成参赛证
        AllContentEntity all = null;
        // 号码布
        AllContentEntity numberPic = null;
        // 证件+号码布
        if ("2".equals(type)) {
            // 查询用户参赛项目
            List<Map<String, Object>> itemList = spMatchItemTeamUserDao.queryUserItems(spTicketEntity.getUserId(), spTicketEntity.getMatchId());
            List<String> items = new ArrayList<>();
            for (Map<String, Object> item : itemList) {
                System.out.println(item.get("itemName").toString());
                if(StringUtils.isNotBlank(item.get("addr").toString())){
                    items.add(item.get("itemName").toString()+"（"+item.get("addr").toString()+"）");
                }else{
                    items.add(item.get("itemName").toString());
                }
            }
            if("1".equals(picType) || "3".equals(picType)){
                all = ImageTool.xuanshou(
                        spTicketEntity.getMatchName(),
                        spUser.getRealName(),
                        spTicketEntity.getTicket().substring(3, spTicketEntity.getTicket().length()),
                        itemList.size()>0?itemList.get(0).get("groupName").toString():"",
                        spTicketEntity.getTeamName(),
                        spUser.getHeader(),
                        items,
                        spTicketEntity.getPic());
            }
            if("2".equals(picType) || "3".equals(picType)){
                numberPic = ImageTool.haomabu(
                        spTicketEntity.getTeamName(),
                        spTicketEntity.getTicket().substring(3, spTicketEntity.getTicket().length()),
                        spUser.getRealName(),
                        spTicketEntity.getPic3()
                );
            }
        }else{
            String str = spUser.getCompany();
            if(StringUtils.isNotBlank(str)){
                str = str.replaceAll("\\(", "（");
                str = str.replaceAll("\\)", "）");
                // 校验规则：最后一个）后没有其他内容，去掉最后一对（）内的内容;
                if(str.lastIndexOf("）") == str.length() - 1) {
                    str = str.substring(0, str.lastIndexOf("（"));
                }
            }
            all = ImageTool.lingdui(
                    spTicketEntity.getMatchName(),
                    spUser.getRealName(),
                    spTicketEntity.getTicket().substring(3, spTicketEntity.getTicket().length()),
                    spTicketEntity.getTeamName(),
                    str,
                    spUser.getHeader(),
                    spTicketEntity.getPic2());
        }
        if(all!=null){
            String url = ImageTool.drawList(all);
            // 存储证件OSS路径
            System.out.println(url);
            spTicketEntity.setEntryPic(url);
        }
        if(numberPic!=null){
            String numberUrl = ImageTool.drawList(numberPic);
            System.out.println(numberUrl);
            spTicketEntity.setNumberPic(numberUrl);
        }
        spTicketDao.updateById(spTicketEntity);
    }




    /**
     * 查询队员序号
     * */
    private String queryTeamMemberNum(Long matchId,Long teamId) {
        String sql ="" +
                "select COUNT(1) from sp_ticket t\n" +
                "where  " +
                " t.match_id=#{p.matchId} \n" +
                "and t.team_id =#{p.teamId} ";
        Map<String,Object> param = new HashMap();
        param.put("matchId",matchId);
        param.put("teamId",teamId);
        Integer count = commDao.count(sql,param)+1;
        return String.format("%03d",count);
    }

    /**
     * 修改个人赛
     * */
    public Result editPerson(SpMatchItemTeamDTO dto) {
        SpUserDTO cuser = UserContext.getUser();
       ;
        SpMatchItemTeamEntity entity = baseDao.selectById(dto.getId());
        entity.setGroupId(dto.getGroupId());
        baseDao.updateById(entity);
        SpMatchItemTeamUserDTO user = dto.getUsers().get(0);
        //删除所有的老师
        QueryWrapper teacherQe =new QueryWrapper<>().eq("team_Id", dto.getId())
                .eq("type",2);
        teamUserDao.delete(teacherQe);
        //插入指导老师
        if(StringUtils.isNotBlank(user.getTeachers())){
            for(String teacherId : user.getTeachers().split(",")){
                SpMatchItemTeamUserEntity teacher = new SpMatchItemTeamUserEntity();
                teacher.setMatchItemTeamId(entity.getId());
                teacher.setStatus(1);
                teacher.setTeamId(cuser.getTeamId());
                //老师，2是学生
                teacher.setType(2);
                teacher.setUserId(Long.parseLong(teacherId));
                teamUserDao.insert(teacher);
            }
        }
        return new Result();
    }



    public String check( Long userId ,Long groupId ,Long itemId ){
        SpMatchItemEntity spItem =spMatchItemDao.selectById(itemId);
        SpMatchEntity spMatch = spMatchDao.selectById(spItem.getMatchId());
        if(spMatch.getBeginSignup().getTime()>System.currentTimeMillis()||spMatch.getEndSignup().getTime()<System.currentTimeMillis()){
            return "不在报名时间范围内！";
        }
        //省赛国赛校验
        if(spMatch.getMatchLevel()==1||spMatch.getMatchLevel()==2){
            SpBaseMatchItemEntity baseMatchItem = spBaseMatchItemDao.selectById(spItem.getBaseMatchItemId());
             int checkFlag =1;
             //1只能报名一项，2只能报名一项团体，一项个人，3能报名两项
             checkFlag = spMatch.getAllowQty()!=null?spMatch.getAllowQty():1;
             String itemTypeSql = checkFlag==2?" and bi.item_type =#{p.itemType} ":"";
             String sql ="\n" +
                     "select  count(1) from \n" +
                     "sp_match_item_team_user tti\n" +
                     "inner join sp_match_item_team  tt on tti.match_item_team_id = tt.id\n" +
                     "inner join sp_match_item  mi on mi.id = tt.match_item_id\n" +
                     "inner join sp_match m on m.id = mi.match_id\n" +
                     "inner join sp_base_match_item bi on bi.id = mi.base_match_item_id\n" +
                     "where tti.user_id = #{p.userId} and m.match_level = "+spMatch.getMatchLevel()+" and m.season=#{p.session} "+itemTypeSql+" and tti.`status` not in  "+CANCEL_STATUS ;
            ;
            Map<String,Object> param = new HashMap<>();
            param.put("userId",userId);
            param.put("session",spMatch.getSeason());
            param.put("itemType",baseMatchItem.getItemType());
            int count = commDao.count(sql,param);
            if(count>0&&(checkFlag==1)){
                SpUserEntity user =spUserDao.selectById(userId);
                return user.getRealName()+"只可报名1项";
            }if(count>1&&(checkFlag==3)){
                SpUserEntity user =spUserDao.selectById(userId);
                return user.getRealName()+"只可报名2项";
            }
            else if(count>0&&checkFlag ==2 ){
                SpUserEntity user =spUserDao.selectById(userId);
                return user.getRealName()+"只可报名1项个人赛+1项团体赛";
            }
        }
        //查询本赛季已报名的赛事

        //检查是否参加了别的比赛
        String checkOurGroup = checkOtherGroup(userId,groupId,spMatch.getId());
        if(StringUtils.isNotBlank(checkOurGroup)){
            return spUserDao.selectById(userId).getRealName()+"已参加"+checkOurGroup+"组别比赛，不能参加此组别比赛";
        }
        return null;
    }

    /**
     * 检测选手在本赛季是否报名别的组
     * */
    public String checkOtherGroup(Long userId ,Long groupId ,Long matchId ){
        String sql ="\n" +
                "select sd.dict_label name from sp_match_item_team_user su \n" +
                "left join sp_match_item_team stm on su.match_item_team_id = stm.id\n" +
                "left join sp_match_item mi on mi.id = stm.match_item_id\n" +
                "left join sp_match m on m.id = mi.match_id\n" +
                "left join sys_dict_data sd on sd.id = stm.group_id\n" +
                "where su.user_id = #{p.userId } and \n" +
                "stm.group_id != #{p.groupId } \n" +
                //3取消，7弃权，8是驳回
                " and stm.status not in (3,7,8)" +
                "and m.id=#{p.matchId} ";
        Map<String,Object> param = new HashMap<>();
        param.put("userId",userId);
        param.put("groupId",groupId);
        param.put("matchId",matchId);
        List<Map<String,String>> list = commDao.commList(sql,param);
        Map<String,String>r = new HashMap<>();

        r.put("小学低龄组","小学低龄组，小学组，初阶组");
        r.put("小学高龄组","小学高龄组，小学组,初阶组");
        r.put("小学组","小学组，初阶组，小学低龄组，小学高龄组");
        r.put("初阶组","小学组，初阶组，小学低龄组，小学高龄组");

        r.put("初中组","初中组，高阶组");
        r.put("高中组","高中组，高阶组");
        r.put("高阶组","高阶组，初中组，高中组");
        if(list.size()>0){
            SysDictDataEntity dictData = dictDataDao.selectById(groupId);
            String newName = dictData.getDictLabel();
            String newNameRaltion = r.get(newName);
            for(Map<String,String> oldItem : list){
                String oldName = oldItem.get("name");
                if(!newNameRaltion.contains(oldName)){
                    return oldName;
                }
            }
        }
        return null;
    }
    /**
     * 检测报名次数
     * */
    public String checkMatchNumw(Long userId ,Long matchId ,Long matchItemId ){
        String sql ="\n" +
                "select count(1)  from sp_match_item_team_user su \n" +
                "left join sp_match_item_team stm on su.match_item_team_id = stm.id\n" +
                "left join sp_match_item mi on mi.id = stm.match_item_id\n" +
                "left join sp_match m on m.id = mi.match_id\n" +
                "left join sys_dict_data sd on sd.id = stm.group_id\n" +
                "where su.user_id = #{p.userId }  \n" +
                //3取消，7弃权，8是驳回
                " and stm.status not in (3,7,8)" +
                "and m.id=#{p.matchId} ";
        Map<String,Object> param = new HashMap<>();
        param.put("userId",userId);
        param.put("matchId",matchId);
        int count = commDao.count(sql,param);
        if(count >=2){
            return "本次赛事不能参加超过2场赛项";
        }
        String sql2 ="\n" +
                "select count(1)  from sp_match_item_team_user su \n" +
                "left join sp_match_item_team stm on su.match_item_team_id = stm.id\n" +
                "left join sp_match_item mi on mi.id = stm.match_item_id\n" +
                "left join sp_match m on m.id = mi.match_id\n" +
                "left join sys_dict_data sd on sd.id = stm.group_id\n" +
                "where su.user_id = #{p.userId }  \n" +
                " and stm.match_item_id = #{p.matchItemId}" +
                //3取消，7弃权，8是驳回
                " and stm.status not in (3,7,8)" +
                "and m.id=#{p.matchId} ";
        Map<String,Object> param2 = new HashMap<>();
        param2.put("userId",userId);
        param2.put("matchId",matchId);
        param2.put("matchItemId",matchItemId);
        int count2 = commDao.count(sql2,param2);
        if(count2 >=1){
            return "已参加此赛项，不能重复参加";
        }
        return null;
    }


    /**
     * 抽签逻辑
     * @param id
     * @return
     */
    @Override
    public Result draw(Long id) {
        SpMatchItemTeamEntity entity = this.baseDao.selectById(id);
        entity.setSort(entity.getSortPre());
        this.baseDao.updateById(entity);
        return new Result().ok(entity.getSortPre()+"");
    }

    /**
     * 结束抽签
     */
    @Override
    public Result endDraw(Long matchItemId, Long groupId) {
        List<SpMatchItemTeamEntity> list2 = this.baseDao.selectList(
                new QueryWrapper<SpMatchItemTeamEntity>()
                        .eq("match_item_id", matchItemId)
                        .eq("group_id", groupId)
                        .in("status", 1, 2, 4, 5, 6)
                        .eq("sort", 0)
        );
        for(SpMatchItemTeamEntity teamEntity : list2) {
            teamEntity.setSort(teamEntity.getSortPre());
            this.baseDao.updateById(teamEntity);
        }
        return new Result().ok("");
    }

    /**
     * 重新抽签
     */
    @Override
    public Result reDraw(Long matchItemId, Long groupId) {
        List<SpMatchItemTeamEntity> list = this.baseDao.selectList(
                new QueryWrapper<SpMatchItemTeamEntity>()
                        .eq("match_item_id", matchItemId)
                        .eq("group_id", groupId)
                        .in("status", 1, 2, 4, 5, 6)
        );
        for (SpMatchItemTeamEntity teamEntity : list){
            teamEntity.setSort(0);
            teamEntity.setSortPre(0);
            this.baseDao.updateById(teamEntity);
        }

        //把所有参赛队的序号放入一个集合
        List<Integer> sorts = new ArrayList<>();
        for (int i=0; i<list.size(); i++){
            sorts.add(i+1);
        }
        //打乱sorts的顺序
        Collections.shuffle(sorts);

        for(SpMatchItemTeamEntity teamEntity : list){
            if(sorts.size()==0){
                return new Result().error("序号不够");
            }
            teamEntity.setSortPre(sorts.get(0));
            this.baseDao.updateById(teamEntity);
            sorts.removeIf(o->o==sorts.get(0));
        }
        return new Result().ok("");
    }


    /**
     * 管理员推荐晋级、取消推荐晋级
     * @param ids
     * @return
     */
    @Override
    public Result rise(Long[] ids, Integer status) {
        for (Long id : ids){
            SpMatchItemTeamEntity entity = this.baseDao.selectById(id);
            if(status == 1) {
                entity.setIsRise(1);
                entity.setStatus(5);
                entity.setRejectReason("");
            }else{
                entity.setIsRise(0);
                entity.setStatus(4);
            }
            this.baseDao.updateById(entity);
        }
        return new Result();
    }

    /**
     * 申请晋级
     */
    @Override
    @Transactional
    public Result confirmRise(Long id, String riseFile, String promissFile, String users, String groupName, String teamId) {
        List<Long> studentUserId = new ArrayList<>();
        if (StringUtils.isNotBlank(users)) {
            studentUserId = Arrays.asList(users.split(",")).stream().map(v -> Long.parseLong(v)).collect(Collectors.toList());
        }
        SpMatchItemTeamEntity entity = this.baseDao.selectById(id);
        int teamStatus = entity.getStatus();
        String rejectReason = entity.getRejectReason();
        if(teamStatus == 5 && "放弃晋级".equals(rejectReason)){
            return new Result().error("已放弃晋级，如需修改请联系组委会！");
        }

        entity.setIsRise(1);
        entity.setStatus(2);
        // 校验选手、老师都必须在队伍中
        // 4学生  3指导老师
        List<SpTeamUserEntity> teamUserList = spTeamUserDao.selectList(
                new QueryWrapper<SpTeamUserEntity>()
                        .eq("team_id", entity.getTeamId())
                        .in("type", 3, 4)
        );

        List<Long> teamUserListConnection = teamUserList.stream().map(SpTeamUserEntity::getUserId).collect(Collectors.toList());

        // 1学生  2指导老师
        List<SpMatchItemTeamUserEntity> itemTeamUserList = this.spMatchItemTeamUserDao.selectList(new QueryWrapper<SpMatchItemTeamUserEntity>()
                .eq("match_item_team_id", entity.getId())
        );

        //校验itemTeamUserList学生、指导老师都必须在teamUserList队伍中
        for (SpMatchItemTeamUserEntity itemTeamUser : itemTeamUserList) {
            if (itemTeamUser.getType() == 1) {
                if (!teamUserListConnection.contains(itemTeamUser.getUserId())) {
                    return new Result().error("选手不在代表队中");
                }
            }
            if (itemTeamUser.getType() == 2) {
                if (!teamUserListConnection.contains(itemTeamUser.getUserId())) {
                    return new Result().error("指导老师不在代表队中");
                }
            }
        }

        // 晋级后，把晋级队伍的所有成员加入到下一轮比赛的参赛队中
        // todo
        // 查询母赛事
        SpMatchItemEntity matchItem = spMatchItemDao.selectById(entity.getMatchItemId());
        //SpMatchEntity thisMatch = spMatchDao.selectById(matchItem.getMatchId());
        if (matchItem != null) {
            // 当前赛事信息
            SpMatchEntity spMatch = spMatchDao.selectById(matchItem.getMatchId());
            if (spMatch == null) {
                return new Result().error("赛事信息不存在");
            }
            if (spMatch.getMatchParentId() == null) {
                return new Result().error("母赛事不存在");
            }
            // 查询下一轮比赛
            SpMatchItemEntity nextMatchItem = spMatchItemDao.selectOne(
                    new QueryWrapper<SpMatchItemEntity>()
                            .eq("match_id", spMatch.getMatchParentId())
                            .eq("base_match_item_id", matchItem.getBaseMatchItemId())
            );
            if (nextMatchItem == null) {
                return new Result().error("母赛事的赛项不存在");
            }
            // 报名母赛项
            SpMatchItemTeamEntity nextMatchItemTeam = new SpMatchItemTeamEntity();
            BeanUtils.copyProperties(entity, nextMatchItemTeam);
            nextMatchItemTeam.setId(null);
            // 把当前参赛队id记录到上一级赛事的source_id字段
            nextMatchItemTeam.setSourceId(entity.getId());
            // 替换赛项id
            nextMatchItemTeam.setMatchItemId(nextMatchItem.getId().intValue());
            // 待审核
            nextMatchItemTeam.setStatus(0);
            nextMatchItemTeam.setCreateDate(new Date());
            if (StringUtils.isNotBlank(groupName)) {
                nextMatchItemTeam.setTeamName(groupName);
            }
            nextMatchItemTeam.setRiseFile(riseFile);
            nextMatchItemTeam.setPromissFile(promissFile);
            /*QueryWrapper<SpMatchItemTeamEntity> wrapper = new QueryWrapper<>();
            wrapper.eq("match_item_id", nextMatchItem.getId().intValue());
            wrapper.eq("team_name", groupName);
            List<SpMatchItemTeamEntity> list = baseDao.selectList(wrapper);
            if(list.size() > 0){
                return new Result().error("代表队不能重复");
            }*/


            // 查询当前参赛队的所有成员,全部报到上一级
            List<SpMatchItemTeamUserEntity> matchItemTeamUserList = teamUserDao.selectList(
                    new QueryWrapper<SpMatchItemTeamUserEntity>()
                            .eq("match_item_team_id", entity.getId())
            );
            int students = 0;
            int teachers = 0;
            for (SpMatchItemTeamUserEntity matchItemTeamUser : matchItemTeamUserList) {
                int type = matchItemTeamUser.getType();
                matchItemTeamUser.setStatus(6);
                int status = matchItemTeamUser.getStatus();
                // 学生(已获晋级资格)
                if (type == 1 && status == 6) {
                    students++;
                }
                if (type == 2) {
                    teachers++;
                }
            }
            if (studentUserId.size() != 0) {
                students = studentUserId.size();
            }
            if (!(nextMatchItem.getStudentNum() <= students && students <= nextMatchItem.getStudentNumMax())) {
                return new Result().error("晋级后的学生人数不满足范围");
            }
            if (!(nextMatchItem.getTeacherNum() <= teachers && teachers <= nextMatchItem.getTeacherNumMax())) {
                return new Result().error("晋级后的教师人数不满足范围");
            }
            //清空名次
            nextMatchItemTeam.setRanks(null);
            this.baseDao.insert(nextMatchItemTeam);
            this.baseDao.updateById(entity);
            if (matchItemTeamUserList != null && matchItemTeamUserList.size() > 0) {
                for (SpMatchItemTeamUserEntity matchItemTeamUser : matchItemTeamUserList) {
                    // 报名下一轮比赛
                    SpMatchItemTeamUserEntity nextMatchItemTeamUser = new SpMatchItemTeamUserEntity();
                    BeanUtils.copyProperties(matchItemTeamUser, nextMatchItemTeamUser);
                    nextMatchItemTeamUser.setId(null);
                    // 替换参赛队id
                    nextMatchItemTeamUser.setMatchItemTeamId(nextMatchItemTeam.getId());
                    nextMatchItemTeamUser.setCreateDate(new Date());
                    //没选择，则不保存
                    if (matchItemTeamUser.getType() == 1 && !(studentUserId.contains(matchItemTeamUser.getUserId()) || studentUserId.size() == 0)) {
                        continue;
                    }
                    // 校验学生是否已经报了国赛
                    if (matchItemTeamUser.getType() == 1) {
                        int count = teamUserDao.checkUserMatch(matchItemTeamUser.getUserId(), spMatch.getMatchParentId());
                        if (count > 0) {
                            SpUserEntity spUserEntity = spUserDao.selectById(matchItemTeamUser.getUserId());
                            throw new RenException(spUserEntity.getRealName() + "学生已经报名了国赛");
                        }
                    }
                    nextMatchItemTeamUser.setScore(null);
                    nextMatchItemTeamUser.setScore1(null);
                    nextMatchItemTeamUser.setScore2(null);
                    nextMatchItemTeamUser.setGrade(null);
                    //nextMatchItemTeamUser.setRank(null);
                    nextMatchItemTeamUser.setCertificate(null);
                    nextMatchItemTeamUser.setCertificateUrl(null);
                    teamUserDao.insert(nextMatchItemTeamUser);
                }
            }
        }
        return new Result();
    }

    /**
     * 取消晋级
     */
    @Override
    public Result cancleRise(Long id){
        SpMatchItemTeamEntity entity = this.baseDao.selectById(id);
        entity.setIsRise(0);
        entity.setStatus(2);
        entity.setRejectReason("");
        this.baseDao.updateById(entity);
        return new Result();
    }

    /**
     * 修改基本信息
     * @param id  SpMatchItemTeamEntity.id
     * @param users
     * @param groupName
     * @return
     */
    @Override
    public Result updTeamBaseInfo(Long id, String users, String groupName, String teachers) {
        List<Long> studentUserId = new ArrayList<>();
        if (StringUtils.isNotBlank(users)) {
            studentUserId = Arrays.asList(users.split(",")).stream().map(v -> Long.parseLong(v)).collect(Collectors.toList());
        }
        // 移除删除的队员
        List<SpMatchItemTeamUserEntity> matchItemTeamUserList = teamUserDao.selectList(
                new QueryWrapper<SpMatchItemTeamUserEntity>()
                        .eq("match_item_team_id", id)
                        .eq("type", 1)
        );
        SpMatchItemTeamEntity entity = this.baseDao.selectById(id);
        //校验人数是否符合要求
        SpMatchItemEntity matchItem = spMatchItemDao.selectById(entity.getMatchItemId());
        if (!(matchItem.getStudentNum() <= studentUserId.size() && studentUserId.size() <= matchItem.getStudentNumMax())) {
            throw new RenException("学生人数不满足范围");
        }
        // 校验groupName是否重复
        if(StringUtils.isNotBlank(groupName) && !groupName.equals(entity.getTeamName())){
            QueryWrapper<SpMatchItemTeamEntity> wrapper = new QueryWrapper<>();
            wrapper.eq("match_item_id", entity.getMatchItemId());
            wrapper.eq("team_name", groupName);
            List<SpMatchItemTeamEntity> groupNameList = baseDao.selectList(wrapper);
            if (groupNameList.size() > 0) {
                throw new RenException("队伍名称已被使用，请更换!");
            }
            entity.setTeamName(groupName);
        }
        this.baseDao.updateById(entity);
        for (SpMatchItemTeamUserEntity matchItemTeamUser : matchItemTeamUserList) {
            if (!studentUserId.contains(matchItemTeamUser.getUserId())) {
                teamUserDao.deleteById(matchItemTeamUser.getId());
            }
        }

        List<SpMatchItemTeamUserEntity> list = spMatchItemTeamUserDao.selectList(
                new QueryWrapper<SpMatchItemTeamUserEntity>()
                        .eq("match_item_team_id", id)
                        .eq("type", 2)
        );
        // 添加新的指导老师
        if (StringUtils.isNotBlank(teachers)) {
            // 删除原有的指导老师
            for (SpMatchItemTeamUserEntity teamUserEntity : list) {
                spMatchItemTeamUserDao.deleteById(teamUserEntity.getId());
            }
            String[] teacher = teachers.split(",");
            for (String teacherId : teacher) {
                SpMatchItemTeamUserEntity teamUser = new SpMatchItemTeamUserEntity();
                teamUser.setMatchItemTeamId(id);
                teamUser.setTeamUserId(Long.parseLong(teacherId));
                teamUser.setUserId(Long.parseLong(teacherId));
                teamUser.setTeamId(list.get(0).getTeamId());
                teamUser.setStatus(1);
                teamUser.setType(2);
                spMatchItemTeamUserDao.insert(teamUser);
            }
        }
        return new Result();
    }


    /**
     * 后台通过Excel导入的，需要领队确认晋级
     * 确认晋级
     */
    @Override
    @Transactional
    public Result confirmRise2(Long id,String riseFile, String promissFile ,String users,String groupName){
        List<Long> studentUserId =new ArrayList<>();
        if(StringUtils.isNotBlank(users)){
            studentUserId = Arrays.asList(users.split(",")).stream().map(v->Long.parseLong(v)).collect(Collectors.toList());
        }
        SpMatchItemTeamEntity entity = this.baseDao.selectById(id);
        entity.setIsRise(0);
        entity.setStatus(1);
        if(StringUtils.isNotBlank(groupName)){
            entity.setTeamName(groupName);
        }else{
            entity.setTeamName("");
        }
        entity.setRiseFile(riseFile);
        entity.setRiseTime(new Date());
        entity.setPromissFile(promissFile);
        this.baseDao.updateById(entity);
        //替换选手信息
        this.replaceUser(entity, studentUserId, null);
        return new Result();
    }

    /**
     * 重新上传报名表
     * @param id
     * @param riseFile
     * @return
     */
    @Override
    @Transactional
    public Result reUploadRiseFile(Long id,String riseFile, String promissFile, String users,String groupName,String teachers) {
        List<Long> studentUserId = new ArrayList<>();
        if (StringUtils.isNotBlank(users)) {
            studentUserId = Arrays.asList(users.split(",")).stream().map(v -> Long.parseLong(v)).collect(Collectors.toList());
        }

        SpMatchItemTeamEntity entity = this.baseDao.selectById(id);
        entity.setRiseFile(riseFile);
        entity.setPromissFile(promissFile);
        entity.setRiseTime(new Date());
        if(StringUtils.isNotBlank(groupName)) {
            entity.setTeamName(groupName);
        }
        // 国赛-已被审核为“报名成功”后，只可重传一次报名表
        if (entity.getStatus() != 0) {
            entity.setRiseTimes(entity.getRiseTimes() + 1);
        }
        this.baseDao.updateById(entity);
        //替换选手信息
        this.replaceUser(entity, studentUserId, teachers);
        //替换指导老师
        if (StringUtils.isNotBlank(teachers)) {
            List<SpMatchItemTeamUserEntity> list = spMatchItemTeamUserDao.selectList(
                    new QueryWrapper<SpMatchItemTeamUserEntity>()
                            .eq("match_item_team_id", id)
                            .eq("type", 2)
            );
            // 删除原有的指导老师
            for (SpMatchItemTeamUserEntity teamUserEntity : list) {
                spMatchItemTeamUserDao.deleteById(teamUserEntity.getId());
            }
            String[] teacher = teachers.split(",");
            for (String teacherId : teacher) {
                SpMatchItemTeamUserEntity teamUser = new SpMatchItemTeamUserEntity();
                teamUser.setMatchItemTeamId(id);
                teamUser.setTeamUserId(Long.parseLong(teacherId));
                teamUser.setUserId(Long.parseLong(teacherId));
                teamUser.setTeamId(list.get(0).getTeamId());
                teamUser.setStatus(1);
                teamUser.setType(2);
                spMatchItemTeamUserDao.insert(teamUser);
            }
        }
        return new Result();
    }

    /**
     * 替换报名记录里的选手信息
     * @param entity
     * @param studentUserId
     */
    public void replaceUser(SpMatchItemTeamEntity entity, List<Long> studentUserId, String teacherNames){
        // 查询当前比赛
        SpMatchItemEntity matchItem = spMatchItemDao.selectById(entity.getMatchItemId());
        // 查询当前参赛队的所有成员
        List<SpMatchItemTeamUserEntity> matchItemTeamUserList = teamUserDao.selectList(
                new QueryWrapper<SpMatchItemTeamUserEntity>()
                        .eq("match_item_team_id", entity.getId())
        );
        int students = 0;
        int teachers = 0;
        for(SpMatchItemTeamUserEntity matchItemTeamUser : matchItemTeamUserList) {
            int type = matchItemTeamUser.getType();
            // 学生(已获晋级资格)
            if (type == 1 ) {
                students++;
            }
            if (type == 2) {
                teachers++;
            }
        }

        if(studentUserId.size() !=0 ){
            students = studentUserId.size();
        }
        if(!(matchItem.getStudentNum()<=students && students<=matchItem.getStudentNumMax())) {
            throw new RenException("晋级后的学生人数不满足范围");
        }
        if(StringUtils.isNotBlank(teacherNames)){
            teachers = teacherNames.split(",").length;
        }
        if(!(matchItem.getTeacherNum()<=teachers && teachers<=matchItem.getTeacherNumMax())) {
            throw new RenException("晋级后的教师人数不满足范围");
        }

        // 查询当前参赛队的所有选手
        List<SpMatchItemTeamUserEntity> studentList = teamUserDao.selectList(
                new QueryWrapper<SpMatchItemTeamUserEntity>()
                        .eq("match_item_team_id", entity.getId())
                        .eq("type", 1)
        );
        // 比对matchItemTeamUserList和users，如果matchItemTeamUserList中有，users中没有，则删除
        for(SpMatchItemTeamUserEntity t: studentList){
            for(Long u: studentUserId){
                if(t.getUserId().equals(u)){
                    break;
                }
                if(u.equals(studentUserId.get(studentUserId.size()-1))){
                    teamUserDao.deleteById(t.getId());
                }
            }
        }
    }

    @Override
    @SeasonFilter(tableAlias = "mc")
    public PageData<Map> signRecord(Map<String, Object> params){
        Page page = createPage(params);
        //分页参数
        params.put(Constant.PAGE, page);
        IPage<Map<String,Object>> page2 = this.baseDao.signRecord(page, params);
        PageData<Map> pageData = new PageData(page2.getRecords(),page2.getTotal());
        return pageData;
    }

    @Override
    @SeasonFilter(tableAlias = "mc")
    public PageData<Map> signRecordRise(Map<String, Object> params){
        Page page = createPage(params);
        //分页参数
        params.put(Constant.PAGE, page);
        IPage<Map<String,Object>> page2 = this.baseDao.signRecordRise(page, params);
        PageData<Map> pageData = new PageData(page2.getRecords(),page2.getTotal());
        return pageData;
    }

    @Override
    public Result pass(Long[] ids, Integer status,String rejectReason) {
        for (Long id : ids){
            SpMatchItemTeamEntity entity = this.baseDao.selectById(id);
            //1审核通过  8驳回
            entity.setStatus(status);
            if(StringUtils.isNotBlank(rejectReason)){
                entity.setRejectReason(rejectReason);
            }else{
                entity.setRejectReason("");
            }
            this.baseDao.updateById(entity);
            //生成证件，审核通过不生成，放在了定时任务生成
            /*try {
                String errorMsg = generateCard(entity.getId());
                if (StringUtils.isNotBlank(errorMsg)) {
                    return new Result().error(errorMsg);
                }
            }catch (Exception e){
                e.printStackTrace();
                return new Result().error("生成证件失败");
            }*/

        }
        return new Result();
    }


    @Override
    public PageData<Map> groupCount(Map<String, Object> params){
        Page page = createPage(params);
        //分页参数
        params.put(Constant.PAGE, page);
        IPage<Map<String,Object>> page2 = this.baseDao.groupCount(page, params);
        PageData<Map> pageData = new PageData(page2.getRecords(),page2.getTotal());
        return pageData;
    }

    /**
     * 下载证书
     *
     * @param
     * @param response
     * @throws Exception
     */
    @Override
    public Result<String> downloadFile(Map<String, Object> params, HttpServletResponse response) throws Exception {
        Page page = new Page();
        page.setCurrent(0);
        page.setSize(2500);
        IPage<Map<String,Object>> signDocumentVOS = this.spTicketDao.queryTicketBy(page, params);;
        List<Map<String,Object>> list = signDocumentVOS.getRecords();
        //list移除集合中entryPic字段等于空的数据
        List<Map<String, Object>> urlList = new ArrayList<>();
        //type 1参赛证 2号码布
        String picType = (String)params.get("picType");
        //把list中的entryPic字段不为空的取出来放到urlList中
        Map<String, Object> urlMap = null;
        for (Map<String, Object> map : list) {
            //type 1参赛证 2号码布
            if("1".equals(picType)){
                if (map.get("entryPic") != null) {
                    urlMap = new HashMap<>();
                    urlMap.put("url", map.get("entryPic"));
                    urlMap.put("ticket", map.get("ticket"));
                    urlList.add(urlMap);
                }
            }else{
                if (map.get("numberPic") != null) {
                    urlMap = new HashMap<>();
                    urlMap.put("url", map.get("numberPic"));
                    urlMap.put("ticket", map.get("ticket"));
                    urlList.add(urlMap);
                }
            }
        }

        if(list.size()>0) {
            //清空输出流
            response.reset();
            //定义输出类型
            response.setContentType("application/octet-stream");
            Map<String,Object> map = list.get(0);
            // 赛事+筛选条件+参赛证/号码布+月日.zip
            String teamName = (String)params.get("teamName");
            String realName = (String)params.get("realName");
            String ticket = (String)params.get("ticket");
            String province = (String)params.get("province");
            String groupId = (String)params.get("groupId");
            String city = (String)params.get("city");
            //String title = (String)map.get("matchName") + teamName + realName + ticket + "参赛证" + DateUtils.format(new Date(),"MMdd")+ ".zip";
            String title = ("1".equals(picType)?"参赛证":"号码布") + "-" + teamName + realName + ticket + groupId + "-" + province + "-" + city +"-"+ DateUtils.format(new Date(),"MMdd")+ ".zip";
            // 编译成utf-8格式
            title = URLEncoder.encode(title,"UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + title + ";" + "filename*=utf-8''" + title);
            // 打包下载
            ZipUtils.getZipFile(IOUtils.getByte(urlList), response.getOutputStream(), response);
            return new Result<String>().ok("下载成功");
        }else {
            return new Result<String>().error("没有可下载的数据");
        }
    }


    /**
     * 证书查询、导出
     * @param params
     * @return
     */
    @Override
    public PageData<Map> queryCertificate(Map<String, Object> params){
        Page page = createPage(params);
        //分页参数
        params.put(Constant.PAGE, page);
        IPage<Map<String,Object>> page2 = this.baseDao.queryCertificate(page, params);
        PageData<Map> pageData = new PageData(page2.getRecords(),page2.getTotal());
        return pageData;
    }

    /**
     * 查询选手荣誉证书
     * @param params
     * @return
     */
    @Override
    public List<Map<String,Object>> queryStudentCerBy(Map<String, Object> params){
        List<Map<String,Object>> list = spCertificateImportDao.queryCertificateBy(params);

        for(Map<String, Object> map : list){
            //查询指导老师
            String teacher = "";
            //线上报名的需要查老师
            String type  = (String) map.get("type");
            if("1".equals(type)) {
                if (StringUtils.isEmpty((String) map.get("teacher"))) {
                    //查询老师
                    List<SpMatchItemTeamUserEntity> teacherList = spMatchItemTeamUserDao.selectList(
                            new QueryWrapper<SpMatchItemTeamUserEntity>()
                                    .eq("match_item_team_id", map.get("matchItemTeamId"))
                                    .eq("type", 2)
                    );
                    for (SpMatchItemTeamUserEntity entity : teacherList) {
                        SpUserEntity spUser = spUserDao.selectById(entity.getUserId());
                        teacher += spUser.getRealName() + " ";
                    }
                }
                map.put("teacher", teacher);
            }
        }
        return list;
    }

    @Override
    public List<Map<String,Object>> queryTeacherCerBy(Map<String, Object> params){
        return spCertificateImportDao.queryTeacherCerBy(params);
    }


    /**
     * 根据id查询附件并下载
     *
     * @param
     * @param response
     * @throws Exception
     */
    @Override
    public Result<String> downloadCertificate(Map<String, Object> params, HttpServletResponse response) throws Exception {
        Page page = new Page();
        page.setCurrent(1);
        page.setSize(2000);
        // 签署标题 也就是压缩包名称
        String title = "";
        String matchItemId = (String)params.get("matchItemId");
        String groups = (String)params.get("groups");
        String grade = (String)params.get("grade");
        String company = (String)params.get("company");
        title += matchItemId;
        if(StringUtils.isNotEmpty(groups)){
            title += "-" + groups;
        }
        if(StringUtils.isNotEmpty(grade)){
            title += "-" + grade;
        }
        if(StringUtils.isNotEmpty(company)){
            title += "-" + company;
        }
        title += "-选手获奖证书.zip";
        // 编译成utf-8格式
        title = URLEncoder.encode(title,"UTF-8");
        IPage<Map<String,Object>> signDocumentVOS = this.baseDao.queryCertificate(page, params);
        List<Map<String,Object>> list = signDocumentVOS.getRecords();
        for(Map<String,Object> map : list){
            String bh = map.get("realName") + "-" + map.get("certificate");
            map.put("ticket", bh);
        }
        //list移除集合中url字段等于空的数据
        list.removeIf(map -> map.get("url") == null);
        if(list.size()>0) {
            //清空输出流
            response.reset();
            //定义输出类型
            response.setContentType("application/octet-stream");
            response.setHeader("Content-disposition", "attachment;filename=" + title + ";" + "filename*=utf-8''" + title);
            // 打包下载
            ZipUtils.getZipFile(IOUtils.getByte(signDocumentVOS.getRecords()), response.getOutputStream(), response);
            return new Result<String>().ok("下载成功");
        }else {
            return new Result<String>().error("没有可下载的数据");
        }
    }

    @Override
    public PageData<Map> matchScoreRecord(Map<String, Object> params){
        Page page = createPage(params);
        //分页参数
        params.put(Constant.PAGE, page);
        IPage<Map<String,Object>> page2 = this.baseDao.matchScoreRecord(page, params);
        PageData<Map> pageData = new PageData(page2.getRecords(),page2.getTotal());
        return pageData;
    }

    /**
     * 后台生成荣誉证书图片
     *
     * @param params
     */
    public void certificate(Map<String, Object> params){
        Page page = createPage(params);
        page.setSize(20000);
        //分页参数
        params.put(Constant.PAGE, page);
        IPage<Map<String,Object>> page2 = this.baseDao.matchScoreRecord(page, params);
        List<Map<String,Object>> list = page2.getRecords();
        for (Map<String,Object> map : list) {
            //生成证书
            try {
                // 组装数据
                String no = (String) map.get("certificate");
                if (StringUtils.isEmpty(no)) {
                    continue;
                }
                String certificateUrl = (String) map.get("certificateUrl");
                if (StringUtils.isNotBlank(certificateUrl)) {
                    continue;
                }
                String realName = (String) map.get("realName");
                //名字长度小于5个字的才能生成，大于等于5个字的手动线下生成
                if (realName.length() >= 5) {
                    continue;
                }
                String item = (String) map.get("item");
                String group = (String) map.get("dictLabel");
                String grade = (String) map.get("grade");
                String company = (String) map.get("userCompany");
                String matchName = "同学在" + map.get("matchName") + "中荣获";
                Integer endDate = (Integer) map.get("endDate");
                String itemClassify = (String) map.get("itemClassify");
                // 1518593958401269779 操控类  1518593958401269780编程类
                String itemType = "";
                if ("1518593958401269779".equals(itemClassify)) {
                    itemType = "操控类";
                } else if ("1518593958401269780".equals(itemClassify)) {
                    itemType = "编程类";
                } else if ("1518593958401269781".equals(itemClassify)) {
                    itemType = "组合类";
                } else if ("1518593958401269782".equals(itemClassify)) {
                    itemType = "虚拟类";
                } else if ("1518593958401269783".equals(itemClassify)) {
                    itemType = "创意类";
                } else if ("100101".equals(itemClassify)) {
                    itemType = "旋翼类";
                } else if ("100102".equals(itemClassify)) {
                    itemType = "固定翼类";
                } else if ("100103".equals(itemClassify)) {
                    itemType = "创意类";
                }

                // teamName 截取字符串中最后一个括号之前的内容
                /*if(StringUtils.isNotBlank(company)){
                    company = company.replaceAll("\\(", "（");
                    company = company.replaceAll("\\)", "）");
                    // 校验规则：最后一个）后没有其他内容，去掉最后一对（）内的内容;
                    if(company.lastIndexOf("）") == company.length() - 1) {
                        company = company.substring(0, company.lastIndexOf("（"));
                    }
                }*/
                String pic4 = (String) map.get("pic4");
                if(StringUtils.isEmpty(pic4)){
                    System.out.println("error:背景图为空");
                }
                String teacher = "";
                String ercode = QrCodeCreateUtil.genGR("http://login.int-ede.com/renren-admin/front/spuser/t/" + no);
                //获取指导老师
                List<SpMatchItemTeamUserEntity> teacherList = this.spMatchItemTeamUserDao.selectList(
                        new QueryWrapper<SpMatchItemTeamUserEntity>()
                                .eq("match_item_team_id", map.get("matchItemTeamId"))
                                .eq("type", 2)
                );
                if (teacherList.size() > 0) {
                    for (SpMatchItemTeamUserEntity teacherEntity : teacherList) {
                        SpUserEntity spUserEntity = this.spUserDao.selectById(teacherEntity.getUserId());
                        teacher += spUserEntity.getRealName() + "、";
                    }
                    if (teacher.contains("、")) {
                        teacher = teacher.substring(0, teacher.length() - 1);
                    }
                }
                //AllContentEntity all = ImageTool.rongyu(no,realName,item,group,grade,company,teacher,ercode,pic4);
                AllContentEntity all = ImageTool2.rongyu(matchName, no, realName, itemType + "/" + item, group, grade, company, teacher, ercode, pic4, endDate);
                // 遍历数据并画图片
                String url = ImageTool2.drawList(all);
                SpMatchItemTeamUserEntity spMatchItemTeamEntity = new SpMatchItemTeamUserEntity();
                spMatchItemTeamEntity.setId((Long) map.get("id"));
                spMatchItemTeamEntity.setCertificateUrl(url);
                spMatchItemTeamUserDao.updateById(spMatchItemTeamEntity);
                // 修改group状态
                SpMatchItemTeamEntity teamEntity = new SpMatchItemTeamEntity();
                teamEntity = this.baseDao.selectById((Long) map.get("matchItemTeamId"));
                //2完赛
                teamEntity.setStatus(2);
                this.baseDao.updateById(teamEntity);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 后台生成指导老师荣誉证书图片
     *
     * @param params
     */
    public void certificateTeacher(Map<String, Object> params){
        Page page = createPage(params);
        page.setSize(20000);
        //分页参数
        params.put(Constant.PAGE, page);
        IPage<Map<String,Object>> page2 = this.baseDao.signRecordTeacher(page, params);
        List<Map<String,Object>> list = page2.getRecords();
        for (Map<String,Object> map : list){
            //生成证书
            try {
                String grade = map.get("grade") + "";
                if(!(grade.contains("一等奖") || grade.contains("二等奖") || grade.contains("三等奖") )){
                    continue;
                }
                // 组装数据
                String no = (String)map.get("certificate");
                if(StringUtils.isEmpty(no)){
                    continue;
                }
                String certificateUrl = (String)map.get("certificate_url");
                if(StringUtils.isNotBlank(certificateUrl)){
                    continue;
                }
                String realName = (String)map.get("realName");
                //名字长度小于5个字的才能生成，大于等于5个字的手动线下生成
                if(realName.length() >= 5){
                    continue;
                }
                Integer baseMatchItemId = (Integer)map.get("baseMatchItemId");
                String pic5 = (String)map.get("pic5");
                String  ercode = QrCodeCreateUtil.genGR("http://login.int-ede.com/renren-admin/front/spuser/tr/" + no);

                SpBaseMatchItemEntity spBaseMatchItemEntity = spBaseMatchItemDao.selectById(baseMatchItemId);
                SysDictDataEntity sysDictDataEntity = dictDataDao.selectById(spBaseMatchItemEntity.getItemClassify());
                String item = sysDictDataEntity.getDictLabel() +"/" + spBaseMatchItemEntity.getItemName();

                AllContentEntity all = ImageTool.rongyuTeacher(no,realName,item,ercode,pic5);
                // 遍历数据并画图片
                String url = ImageTool.drawList(all);
                String idstr = (String)map.get("id");
                String ids[] = idstr.split(",");
                for(String id: ids) {
                    SpMatchItemTeamUserEntity spMatchItemTeamUserEntity = new SpMatchItemTeamUserEntity();
                    spMatchItemTeamUserEntity.setId(Long.parseLong(id));
                    spMatchItemTeamUserEntity.setCertificateUrl(url);
                    spMatchItemTeamUserDao.updateById(spMatchItemTeamUserEntity);

                    List<SpMatchItemTeamUserEntity> teacherList = spMatchItemTeamUserDao.selectList(
                            new QueryWrapper<SpMatchItemTeamUserEntity>().eq("certificate", no)
                    );
                    for(SpMatchItemTeamUserEntity teacher : teacherList){
                        teacher.setCertificateUrl(url);
                        spMatchItemTeamUserDao.updateById(teacher);
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    @Override
    public void delCertificate(String id){
        SpMatchItemTeamUserEntity entity = new SpMatchItemTeamUserEntity();
        entity.setId(Long.parseLong(id));
        entity.setCertificate("");
        entity.setCertificateUrl("");
        this.spMatchItemTeamUserDao.updateById(entity);
    }

    @Override
    @Transactional
    public void cancelCertificateNo(String id){
        SpMatchItemTeamUserEntity entity = new SpMatchItemTeamUserEntity();
        entity.setId(Long.parseLong(id));
        entity.setCertificate("");
        entity.setCertificateUrl("");
        //删除证书编号，状态变为”报名成功“
        SpMatchItemTeamUserEntity mituEntity = spMatchItemTeamUserDao.selectById(id);
        SpMatchItemTeamEntity matchItemTeamEntity = this.baseDao.selectById(mituEntity.getMatchItemTeamId());
        matchItemTeamEntity.setStatus(1);
        this.baseDao.updateById(matchItemTeamEntity);

        this.spMatchItemTeamUserDao.updateById(entity);
    }

    /**
     * 生成选手荣誉证书编号
     * @param params
     * @return
     */
    @Override
    public Map<String, Object> createCertificateNo(Map<String, Object> params){
        Map<String, Object> result = new HashMap<>();
        result.put("code", 0);
        Page page = createPage(params);
        page.setSize(3000);
        //分页参数
        params.put(Constant.PAGE, page);
        IPage<Map<String,Object>> page2 = this.baseDao.signRecordStudent(page, params);
        List<Map<String,Object>> list = page2.getRecords();
        // 获取赛项id
        String matchItemId = (String)params.get("matchItemId");
        String groupId = (String)params.get("groupId");
        // 有手机号表示是单独生成的
        if(params.get("phone")!=null){
            if(list.size()>0){
                 groupId = list.get(0).get("groupId") + "";
            }
        }

        // 小学低龄组\小学高龄组 共用编号
        if("100304".equals(groupId) || "100305".equals(groupId)){
            groupId = "0";
        }
        // 获取赛项下最大编号
        Double maxForNo =  certificateNoUtils.queryTeamMemberNum(Long.parseLong(matchItemId), Long.parseLong(groupId), "S", null);

        // 后四位流水号
        String lastForNo = "";
        // 循环生产证书编码
        for (int i=0; i<list.size(); i++){
            Map<String,Object> map = list.get(i);
            String grade = (String)map.get("grade");
            //奖等为空、带有'/'不生成
            /*if(StringUtils.isEmpty(grade) || grade.contains("/")){
                continue;
            }*/
            if(StringUtils.isEmpty(grade)){
                continue;
            }
            // 一等奖、二等奖、三等奖、优秀奖才生成
            if(!(grade.contains("一等奖") || grade.contains("二等奖") || grade.contains("三等奖") || grade.contains("优秀奖"))){
                continue;
            }
            //证书已生成不生成
            if(map.get("certificate")!=null && !"".equals(map.get("certificate"))){
                continue;
            }
            // 编号顺序往后加
            lastForNo = String.format("%04d", maxForNo.intValue());
            // 生成证书编号
            Result<String> cerData = certificateNoUtils.getCertificateNo((Long)map.get("matchItemTeamId"), "S", lastForNo);
            if(cerData.getCode()!=0){
                result.put("msg", cerData.getMsg());
                result.put("code", cerData.getCode());
                break;
            }
            // 报错的话跳过
            SpMatchItemTeamUserEntity spMatchItemTeamEntity = new SpMatchItemTeamUserEntity();
            spMatchItemTeamEntity.setId((Long)map.get("id"));
            spMatchItemTeamEntity.setCertificate(cerData.getData());
            this.spMatchItemTeamUserDao.updateById(spMatchItemTeamEntity);
            //刷成完赛
            SpMatchItemTeamEntity matchItemTeamEntity = this.baseDao.selectById((Long)map.get("matchItemTeamId"));
            matchItemTeamEntity.setStatus(2);
            matchItemTeamEntity.setIsRise(0);
            this.baseDao.updateById(matchItemTeamEntity);
            maxForNo++;
        }
        result.put("data", page2.getRecords());
        return result;
    }

    /**
     * 生成指导老师荣誉证书编号
     * @param params
     * @return
     */
    @Override
    public List<Map<String,Object>> createCertificateNoTeacher(Map<String, Object> params){
        Page page = createPage(params);
        page.setSize(3000);
        //分页参数
        params.put(Constant.PAGE, page);
        IPage<Map<String,Object>> page2 = this.baseDao.signRecordTeacher(page, params);
        List<Map<String,Object>> list = page2.getRecords();
        // 获取赛项id
        String matchItemId = (String)params.get("matchItemId");
        // 获取赛事ID
        Long matchId = null;
        if (list!=null && list.size()>0){
            Map<String,Object> map = list.get(0);
            matchId = (Long)map.get("matchId");
        }
        // 获取赛项下最大编号
        Double maxForNo =  certificateNoUtils.queryTeamMemberNum(Long.parseLong(matchItemId), null, "T", matchId);
        // 后四位流水号
        String lastForNo = "";
        // 循环生产证书编码
        for (int i=0; i<list.size(); i++){
            Map<String,Object> map = list.get(i);
            String grade = map.get("grade") + "";
            if(!(grade.contains("一等奖") || grade.contains("二等奖") || grade.contains("三等奖") )){
                continue;
            }

            String idStr = (String)map.get("id");
            // 编号顺序往后加
            lastForNo = String.format("%04d", maxForNo.intValue());
            String ids[] = idStr.split(",");
            Long teamId = (Long)map.get("teamId");
            // 生成证书编号
            Result<String> result = certificateNoUtils.getCertificateNoTeacher(matchId, teamId, matchItemId, lastForNo);
            // 循环ids
            for(String id : ids){
                SpMatchItemTeamUserEntity userEntity = spMatchItemTeamUserDao.selectById(id);
                if(userEntity!=null && StringUtils.isNotEmpty(userEntity.getCertificate())){
                    //存在编号不修改
                }else{
                    SpMatchItemTeamUserEntity spMatchItemTeamEntity = new SpMatchItemTeamUserEntity();
                    spMatchItemTeamEntity.setId(Long.parseLong(id));
                    spMatchItemTeamEntity.setCertificate(result.getData());
                    this.spMatchItemTeamUserDao.updateById(spMatchItemTeamEntity);
                }

                Long userId = userEntity.getUserId();
                List<Map<String,Object>> teacherList = baseDao.queryTeacherBy(userId, matchItemId);
                for(Map<String,Object> teacher : teacherList){
                    SpMatchItemTeamUserEntity spMatchItemTeamEntity = new SpMatchItemTeamUserEntity();
                    spMatchItemTeamEntity.setId(Long.parseLong(teacher.get("id")+""));
                    spMatchItemTeamEntity.setCertificate(result.getData());
                    spMatchItemTeamUserDao.updateById(spMatchItemTeamEntity);
                }
            }

            maxForNo++;
        }
        return page2.getRecords();
    }

    /**
     * 删除group，并把group下的所有人员删除
     * @param ids
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delMatchItemTeam(Long[] ids){
        for(Long id : ids){
            SpMatchItemTeamEntity teamEntity = this.baseDao.selectById(id);
            Long matchId = null;
            if(teamEntity!=null){
                // 获取赛事id
                Integer matchItemId = teamEntity.getMatchItemId();
                SpMatchItemEntity itemEntity = this.spMatchItemDao.selectById(matchItemId);
                if(itemEntity!=null){
                    matchId = itemEntity.getMatchId();
                }
            }

            // 查询group下的成员
            List<SpMatchItemTeamUserEntity> userList = this.spMatchItemTeamUserDao.selectList(
                    new QueryWrapper<SpMatchItemTeamUserEntity>().eq("match_item_team_id",id));

            // 记录需要重新生成参赛证的选手
            List<Long> reGenerateNoList = new ArrayList<>();

            for (SpMatchItemTeamUserEntity user : userList){
                int type = user.getType();
                // 1选手 只有选手判断是否有多个赛项
                if(type==1){
                    // 查询当前选手是否参加多个赛项，如果有则需要重新生成证件
                    /*List<SpMatchItemTeamUserEntity> list = this.spMatchItemTeamUserDao.selectList(
                            new QueryWrapper<SpMatchItemTeamUserEntity>()
                                    .eq("user_id",user.getUserId())
                    );*/
                    List<Map<String,Object>> list = this.spMatchItemTeamDao.queryTeamUserByUserId(user.getUserId(), matchId);

                    if(list!=null && list.size()>1){
                        reGenerateNoList.add(user.getUserId());
                    }else {
                        // 删除选手参赛证、号码布
                        spTicketDao.delete(new QueryWrapper<SpTicketEntity>().eq("match_id", matchId).eq("user_id", user.getUserId()));
                    }
                }
            }

            // 删除group
            this.baseDao.deleteById(id);

            // 删除group下的人员（包含选手的荣誉证书）
            this.spMatchItemTeamUserDao.delete(new QueryWrapper<SpMatchItemTeamUserEntity>().eq("match_item_team_id",id));

            // reGenerateNoList的选手需要重新生成参赛证
            if(reGenerateNoList.size()>0){
                // todo 调用参赛证的生成逻辑
            }

        }
    }

    /**
     * 修改条目状态，修改条目状态，把弃权的修改成报名成功
     * 		 * 0 审核中
     * 		 * 1报名成功
     * 		 * 2完赛
     * 		 * 3已取消/弃权
     * 		 * 4比赛中
     * 		 * 5已获晋级赛资格
     * 		 * 6晋级成功
     * 		 * 7弃权
     * 		 * 8驳回
     * 		 * 9待确认
     */
    @Override
    public void updateStatus(Long id, Integer status){
        SpMatchItemTeamEntity teamEntity = this.baseDao.selectById(id);
        teamEntity.setStatus(status);
        this.baseDao.updateById(teamEntity);
    }

    @Override
    public PageData<Map> signRecordTeam(Map<String, Object> params){
        Page page = createPage(params);
        //分页参数
        params.put(Constant.PAGE, page);

        //排序字段
        String orderField = (String)params.get(Constant.ORDER_FIELD);
        String order = (String)params.get(Constant.ORDER);

        //前端字段排序
        if(StringUtils.isNotBlank(orderField) && StringUtils.isNotBlank(order)){
            if("ranks".equals(orderField)){
                if(Constant.ASC.equalsIgnoreCase(order)) {
                    params.put("orderField2", "order by -a.ranks desc, a.id");
                }else{
                    params.put("orderField2", "order by -a.ranks asc, a.id");
                }
            }else if("sort".equals(orderField)) {
                if(Constant.ASC.equalsIgnoreCase(order)) {
                    params.put("orderField2", "order by case when a.sort = 0 then 999999 else a.sort end asc, a.id");
                }else{
                    params.put("orderField2", "order by case when a.sort = 0 then 999999 else a.sort end desc, a.id");
                }
            }else{
                if(Constant.ASC.equalsIgnoreCase(order)) {
                    page.addOrder(OrderItem.asc(orderField));
                }else {
                    page.addOrder(OrderItem.desc(orderField));
                }
            }
        }

        IPage<Map<String,Object>> page2 = this.baseDao.signRecordTeam(page, params);
        PageData<Map> pageData = new PageData(page2.getRecords(),page2.getTotal());
        return pageData;
    }

    @Override
    public PageData<Map> signRecordStudent(Map<String, Object> params){
        Page page = createPage(params);
        //分页参数
        params.put(Constant.PAGE, page);

        //排序字段
        String orderField = (String)params.get(Constant.ORDER_FIELD);
        String order = (String)params.get(Constant.ORDER);

        //前端字段排序
        if(StringUtils.isNotBlank(orderField) && StringUtils.isNotBlank(order)){
            if("ranks".equals(orderField)){
                if(Constant.ASC.equalsIgnoreCase(order)) {
                    params.put("orderField", "order by -t.ranks desc, tu.id");
                }else{
                    params.put("orderField", "order by -t.ranks asc, tu.id");
                }
            }else {
                if (Constant.ASC.equalsIgnoreCase(order)) {
                    page.addOrder(OrderItem.asc(orderField));
                } else {
                    page.addOrder(OrderItem.desc(orderField));
                }
            }
        }

        IPage<Map<String,Object>> page2 = this.baseDao.signRecordStudent(page, params);
        PageData<Map> pageData = new PageData(page2.getRecords(),page2.getTotal());
        return pageData;
    }

    /*@Override
    public void ranksSort(Map<String, Object> params){
        Page page = createPage(params);
        page.setPages(1);
        page.setSize(2000);
        // 1.个人飞行赛排序
        params.put("orderField", "order by tu.score desc, tu.id");
        IPage<Map<String,Object>> page2 = this.baseDao.signRecordStudent(page, params);
        //查询指导老师
        for(Map<String,Object> map : page2.getRecords()) {
            map.get("score");
        }
    }*/

    @Override
    public PageData<Map> signRecordTeacher(Map<String, Object> params){
        Page page = createPage(params);
        //分页参数
        params.put(Constant.PAGE, page);
        IPage<Map<String,Object>> page2 = this.baseDao.signRecordTeacher(page, params);
        PageData<Map> pageData = new PageData(page2.getRecords(),page2.getTotal());
        return pageData;
    }

    @Override
    public PageData<Map> exportTeacher(Map<String, Object> params){
        Page page = createPage(params);
        //分页参数
        params.put(Constant.PAGE, page);
        IPage<Map<String,Object>> page2 = this.baseDao.exportTeacher(page, params);
        PageData<Map> pageData = new PageData(page2.getRecords(),page2.getTotal());
        return pageData;
    }



    @Override
    public PageData<Map> queryNoTicketUser(Map<String, Object> params){
        Page page = createPage(params);
        //分页参数
        params.put(Constant.PAGE, page);
        IPage<Map<String,Object>> page2 = this.baseDao.queryNoTicketUser(page, params);
        PageData<Map> pageData = new PageData(page2.getRecords(),page2.getTotal());
        return pageData;
    }

    /**
     * 获取小组下所有成员的成绩
     * @param matchItemTeamId
     * @return
     */
    public Map<String,Object> queryScoreResult(Long matchItemTeamId){
        Map<String,Object> result = new HashMap<>();
        SpMatchItemTeamEntity matchItemTeamEntity = this.baseDao.selectById(matchItemTeamId);
        Map<String, Object> data = this.spMatchItemDao.queryBymatchItemId(matchItemTeamEntity.getMatchItemId().longValue());
        String scores = data.get("scores").toString();
        String[] split = scores.split(",");
        String scoreResult = "";
        String cols[] = new String[split.length];
        for (int i = 0; i < split.length; i++) {
            SysDictDataEntity dictData = dictDataDao.selectOne(
                    new QueryWrapper<SysDictDataEntity>()
                            .eq("dict_value",split[i])
            );
            cols[i] = dictData.getDictLabel();
        }
        //查询当前赛项下的所有选手
        List<SpMatchItemTeamUserEntity> userList = this.spMatchItemTeamUserDao.selectList(
                new QueryWrapper<SpMatchItemTeamUserEntity>()
                        .eq("match_item_team_id",matchItemTeamId)
                        .eq("type",1)
        );
        for(SpMatchItemTeamUserEntity user : userList) {
            for (int i = 0; i < cols.length; i++) {
                if (i == 0) {
                    String score00 = user.getScore00();
                    scoreResult += cols[i] + ":" + user.getScore() + ((StringUtils.isNotEmpty(score00) && !score00.equals("null")) ? "/" + score00 : "");
                }
                if (i == 1) {
                    String score1 = user.getScore1();
                    String score11 = user.getScore11();
                    /*if(StringUtils.isNotEmpty(score1)){
                        // 点换成双撇
                        score1 = score1.replace(".","\"");
                    }
                    if(StringUtils.isNotEmpty(score11)){
                        // 点换成双撇
                        score11 = score11.replace(".","\"");
                    }*/
                    scoreResult += "&nbsp;&nbsp;&nbsp;&nbsp;" + cols[i] + ":" + score1 + ((StringUtils.isNotEmpty(score11) && !score11.equals("null")) ? "/" + score11 : "");
                }
                if (i == 2) {
                    String score22 = user.getScore22();
                    scoreResult += "&nbsp;&nbsp;&nbsp;&nbsp;" + cols[i] + ":" + user.getScore2() + ((StringUtils.isNotEmpty(score22) && !score22.equals("null")) ? "/" + score22 : "");
                }
            }
            result.put("grade", user.getGrade());
            break;
        }
        result.put("score", scoreResult);
        result.put("ranks", matchItemTeamEntity.getRanks());
        return result;
    }

    @Override
    public PageData<Map> exportCerLog(Map<String, Object> params){
        Page page = createPage(params);
        //分页参数
        params.put(Constant.PAGE, page);
        IPage<Map<String,Object>> page2 = this.baseDao.exportCerLog(page, params);
        PageData<Map> pageData = new PageData(page2.getRecords(),page2.getTotal());
        return pageData;
    }

    @Override
    public boolean updateTeacher(SpMatchItemTeamDTO dto) {
        List<SpMatchItemTeamUserEntity> list = spMatchItemTeamUserDao.selectList(
                new QueryWrapper<SpMatchItemTeamUserEntity>()
                        .eq("match_item_team_id", dto.getId())
                        .eq("type", 2)
        );
        // 添加新的指导老师
        String teachers = dto.getTeachers();
        // 删除原有的指导老师
        for(SpMatchItemTeamUserEntity entity : list){
            spMatchItemTeamUserDao.deleteById(entity.getId());
        }
        if(StringUtils.isNotBlank(teachers)){
            String[] teacher = teachers.split(",");
            for(String teacherId : teacher){
                SpMatchItemTeamUserEntity entity = new SpMatchItemTeamUserEntity();
                entity.setMatchItemTeamId(dto.getId());
                entity.setTeamUserId(Long.parseLong(teacherId));
                entity.setUserId(Long.parseLong(teacherId));
                entity.setTeamId(list.get(0).getTeamId());
                entity.setStatus(1);
                entity.setType(2);
                spMatchItemTeamUserDao.insert(entity);
            }
            return true;
        }
        return false;
    }

    // 清除成绩
    @Override
    public void cancleScore(Long id){
        List<SpMatchItemTeamUserEntity> list =  spMatchItemTeamUserDao.selectList(
                new QueryWrapper<SpMatchItemTeamUserEntity>()
                        .eq("match_item_team_id", id)
                        .eq("type", 1)
        );
        //清除得分、用时、名次、奖等
        for(SpMatchItemTeamUserEntity entity : list){
            entity.setScore("");
            entity.setScore1("");
            entity.setScore2("");
            entity.setScore00("");
            entity.setScore11("");
            entity.setScore22("");
            entity.setGrade("");
            spMatchItemTeamUserDao.updateById(entity);
        }
        //清除排名
        this.spMatchItemTeamDao.cancleRanks(id);
    }

    @Override
    public void cancleRanks(Long id){
        //清除排名
        this.spMatchItemTeamDao.cancleRanks(id);
    }

    @Override
    public void cancleUserScore(Long id) {
        SpMatchItemTeamUserEntity entity = this.spMatchItemTeamUserDao.selectById(id);
        //清除得分、用时、名次、奖等
        if ( entity != null) {
            entity.setScore("");
            entity.setScore1("");
            entity.setScore2("");
            entity.setGrade("");
            spMatchItemTeamUserDao.updateById(entity);
        }
    }

    public List<Map<String,Object>> queryTeacherByMatchItemTeamId(Long matchItemTeamId){
        return this.baseDao.queryTeacherByMatchItemTeamId(matchItemTeamId);
    }

    @Override
    public String queryTeacherGroup(Long userId, Long matchItemId) {
        return this.baseDao.queryTeacherGroup(userId, matchItemId);
    }

    /**
     * 查询是否有晋级
     */
    @Override
    public List<SpMatchItemTeamEntity> queryRise(Long teamId){
        return this.baseDao.selectList(new QueryWrapper<SpMatchItemTeamEntity>()
                .eq("team_id", teamId)
                .eq("status", 5)
        );
    }

    @Override
    public void ranksSortSingle(Map<String, Object> params){
        this.baseDao.ranksSortSingle(params);
    }

    @Override
    public void ranksSortSingleProgram(Map<String, Object> params){
        this.baseDao.ranksSortSingleProgram(params);
    }

    @Override
    public void ranksSortTeam(Map<String, Object> params){
        this.baseDao.ranksSortTeam(params);
    }

    @Override
    public void ranksSortTeamFqwd(Map<String, Object> params){
        this.baseDao.ranksSortTeamFqwd(params);
    }

    @Override
    public List<Map<String,Object>> queryAllItemGroup(Long matchId){
        return this.baseDao.queryAllItemGroup(matchId);
    }

}
